package com.jly.Controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jly.Util.Constants;
import com.jly.Util.HttpPOSTUtil;
import com.jly.Util.SignUtil;
import com.jly.Util.util;
import com.jly.model.*;
import jdk.nashorn.internal.ir.IdentNode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Controller
public class IndexController {

    @Value("${com.jly.TicketStatus}")
    private String TicketStatus;

    @Value("${com.jly.ity_operatTime3}")
    private String saleStatus;

    @RequestMapping("/index")
    public String index(Model model){
        User user = new User();
        user.setName("111");
        model.addAttribute("user",user);
        return "index";
    }

    @RequestMapping("/index1")
    public String index1(Model model){
        User user = new User();
        user.setName("222");
        model.addAttribute("user",user);
        return "index::refresh";
    }

    /**
     * 用户点击菜单授权获取openid
     * @param request
     * @param code 用于获取openid的凭证
     * @param state 需要跳转的页面
     * @return
     * @throws Exception
     */
    @RequestMapping("/authorization")
    public String authorization(HttpServletRequest request,String code,String state){
        String openid = null;
        try {
            HttpSession session = request.getSession();
            openid = null;
            if(null==session.getAttribute("openid")){
                openid = util.getOpenid(code);
                session.setAttribute("openid",openid);
                String sql = "select user_realname,user_id from tb_user where user_wechat='" + openid + "'";
                JSONObject json = new JSONObject();
                json.put("accesstoken", sql);
                json.put("code", "A11");
                json = util.sendPost(Constants.URL + "/common/api.do", json);
                if(200==json.getInteger("code")){
                    session.setAttribute("user_id", json.getJSONArray("data").getJSONObject(0).getInteger("user_id"));
                    session.setAttribute("user_realname", json.getJSONArray("data").getJSONObject(0).getInteger("user_realname"));
                }else if(201==json.getInteger("code")){

                }else if(400==json.getInteger("code")){
                    return "error";
                }
            }else{
                openid = session.getAttribute("openid").toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return "redirect:"+state+"?openid="+openid;
        }
    }

    /**
     * 店铺列表
     * @param model
     * @param openid
     * @param request
     * @return
     */
    @RequestMapping("/storeList")
    public String storeList(Model model,String openid,HttpServletRequest request){
        System.out.println(openid);
        openid = "onpiE0QH-TgrmFVVPWCEVdh2Z0Qw";
        StringBuilder sb = new StringBuilder();
        sb.append("select store_NO,store_name,a.store_id,counts,user_realname,TO_DAYS(NOW())-TO_DAYS(store_registerTime) as days from tb_store a");
        sb.append(" left join (select COUNT(1) as counts,store_id from tb_user_store where user_store_status=0 group by store_id) b on a.store_id=b.store_id");
        sb.append(" left join (select store_id,user_realname from tb_user_store c join tb_user d on c.user_id=d.user_id where user_store_status=0 and user_storeJob='店长' group by c.store_id) e on a.store_id=e.store_id");
        sb.append(" where store_status=0 and a.store_id in (select store_id from view_us_u where user_wechat='").append(openid).append("') order by store_id desc");
        JSONObject json = new JSONObject();
        json.put("code", "A11");
        json.put("accesstoken",sb.toString());
        String sign = SignUtil.generateSignature(json);
        json.put("sign", sign);
        String result = HttpPOSTUtil.sendPost(Constants.URL + "/common/api.do", "id="+json.toJSONString());
        json = JSON.parseObject(result);
        if(400!=json.getInteger("code")){
            JSONArray data = json.getJSONArray("data");
            List<StoreList> list = new ArrayList<StoreList>();
            for (int i = 0; i < data.size(); i++) {
                StoreList storeList = JSON.toJavaObject(data.getJSONObject(i), StoreList.class);
                if(util.isEmpty(storeList.getUser_realname())){
                    storeList.setUser_realname("无");
                }
                list.add(storeList);
            }
            model.addAttribute("storeList",list);
        }else{
            return "error";
        }
        return "storeList";
    }

    /**
     * * 订单审核详情查询
     * @param request
     * @param model
     * @param ity_Number
     * @param store_id
     * @param sessionid
     * @return
     */
    @RequestMapping("/AuthTicketDetail")
    public String AuthTicketDetail(HttpServletRequest request,Model model,String ity_Number,String store_id,String sessionid){
        try {
            System.out.println( request.getSession().getId().equals(sessionid));
            String[] typename = {"", "销", "", "维", "退", "调"};
            JSONObject json = new JSONObject();
            json.put("where", " where ity_Number=" + ity_Number);
            json.put("limit", "");
            json = util.sendPost(Constants.URL + "/android/getList.do", json);
            if(400 == json.getInteger("code")){
                return "error";
            }
            if(201 == json.getInteger("code")){
                return "404";
            }
            JSONArray array = json.getJSONArray("data");
            JSONObject jsons = new JSONObject();
            jsons.put("accesstoken", "select store_name from tb_store where store_id=" + store_id);
            jsons.put("code", "A11");
            jsons = util.sendPost(Constants.URL + "/common/api.do", jsons);
            if(200 != json.getInteger("code")){
                return "error";
            }
            String store_name = jsons.getJSONArray("data").getJSONObject(0).getString("store_name");
            PushTicketDetail ptd = null;
            List<Goods> list = new ArrayList<Goods>();
            Integer ity_type = array.getJSONObject(0).getInteger("ity_type");
            ptd = JSON.toJavaObject(util.jsonTrim(array.getJSONObject(0)), PushTicketDetail.class);
            for (int i = 0; i < array.size(); i++) {
                json = array.getJSONObject(i);
                if (i == 0) {
                    ptd.setStore_name(store_name);
                    if(14==ity_type){
                        ptd.setTypename("退");
                    }else {
                        ptd.setTypename(typename[ity_type]);
                    }
                    if(ity_type==1){
                        ptd.setIty_operatTime3(JSON.parseObject(saleStatus).getString(json.getString("ity_operatTime3")));
                    }
                    ptd.setStatus(JSON.parseObject(TicketStatus).getJSONObject((ity_type+"")).getString("ity_operatPerson3"));
                }
                Goods goods = new Goods();
                goods.setGoodsid(json.getString("stock_goodsId"));
                goods.setGoodsSeriesid(json.getString("goodsSeriesid"));
                goods.setType(Constants.GoodsType[(json.getInteger("goodsType")-1)]);
                if(ity_type==1){
                    goods.setBrand(json.getString(Constants.BRAND[(json.getInteger("goodsType") - 1)]));
                    goods.setModel(json.getString(Constants.MODEL[(json.getInteger("goodsType") - 1)]));
                    goods.setStyle(json.getString(Constants.STYLE[(json.getInteger("goodsType") - 1)]));
                }else {
                    goods.setBrand(json.getString("goods_pinming"));
                }
                goods.setColorNumber(json.getString("jobberName"));
                goods.setNumbers(json.getInteger("goodsCounts"));
                goods.setPrice(json.getString("goods_danjia"));
                String[] filearr = Constants.LENS[(json.getInteger("stock_type")-1)];
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("stock_type", json.getInteger("stock_type"));
                for (int j = 0; j < filearr.length; j++) {
                    if(util.isEmpty(json.getString(filearr[j]))){
                       continue;
                    }
                    jsonObject.put(filearr[j], URLEncoder.encode(json.getString(filearr[j]),"utf-8"));
                }
                goods.setJsonObject(jsonObject);
                list.add(goods);
            }
            ptd.setList(list);
            model.addAttribute("info", ptd);
            //销售单需要得到验光和加工信息
            if(ity_type==1){
                Optometry opt = new Optometry();
                model.addAttribute("opt", opt);
                return "saleDetail";
//                Integer ity_targetid = ptd.getIty_targetid();
//                Integer orderItyid = ptd.getOrderItyid();
//                Optometry opt = null;
//                if(null!=ity_targetid){
//                    jsons = new JSONObject();
//                    jsons.put("code", "A11");
//                    jsons.put("accesstoken", "select a.*,b.vip_score,vip_remarks from tb_optometry a join tb_vip b on a.vip_id=b.vip_id where optometry_id="+ity_targetid);
//                    jsons = util.sendPost(Constants.URL + "/common/api.do", jsons);
//                    if(200 == jsons.getInteger("code")){
//                        array = jsons.getJSONArray("data");
//                        opt = JSON.toJavaObject(util.jsonTrim(array.getJSONObject(0)), Optometry.class);
//                    }else if(201 == jsons.getInteger("code")){
//                        ptd.setIty_targetid(null);
//                    }else{
//                        return "error";
//                    }
//                }
//                if(null!=orderItyid){
//
//                }
//                model.addAttribute("opt", opt);
//                model.addAttribute("info", ptd);
//                return "saleDetail";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "AuthTicketDetail";
    }

    /**
     * 商品详情
     * @param goodsinfo 商品信息
     * @return
     */
    @RequestMapping("/GoodsDetail")
    public String GoodsDetail(Model model,String goodsinfo){
        try {
            JSONObject json = JSON.parseObject(goodsinfo);
            Integer type = json.getInteger("stock_type");
            JSONArray arr = new JSONArray();
            String[] filearr = Constants.LENS[(type-1)];
            for (int i = 0; i < filearr.length; i++) {
                arr.add(json.getString(filearr[i]));
            }
            model.addAttribute("arr", arr);
            model.addAttribute("type", type);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "GoodsDetail";
    }

    /**
     * 销售单详情查询加工单信息
     * @param model
     * @param ity_targetid
     * @return
     */
    @RequestMapping("/findOpt")
    public String findOpt(Model model,String ity_targetid){
        try {
            Optometry opt = null;
            JSONObject jsons = new JSONObject();
            jsons.put("code", "A11");
            jsons.put("accesstoken", "select a.*,b.vip_score,vip_remarks from tb_optometry a join tb_vip b on a.vip_id=b.vip_id where optometry_id="+ity_targetid);
            jsons = util.sendPost(Constants.URL + "/common/api.do", jsons);
            if(200 == jsons.getInteger("code")){
                JSONArray array = jsons.getJSONArray("data");
                opt = JSON.toJavaObject(util.jsonTrim(array.getJSONObject(0)), Optometry.class);
            }else if(201 == jsons.getInteger("code")){

            }else{
                return "error";
            }
            model.addAttribute("opt", opt);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "saleDetail::opt_refresh";
    }

    /**
     * 销售单详情查询加工单
     * @param model
     * @param orderItyid
     * @return
     */
    @RequestMapping("/findJG")
    public String findJG(Model model,String orderItyid){
        try {
            Optometry opt = null;
            JSONObject jsons = new JSONObject();
            jsons.put("ity_id", orderItyid);
            jsons = util.sendPost(Constants.URL + "/android/getJGDetail.do", jsons);
            if(200 == jsons.getInteger("code")){
                JSONArray array = jsons.getJSONArray("data");
                opt = JSON.toJavaObject(util.jsonTrim(array.getJSONObject(0)), Optometry.class);
            }else if(201 == jsons.getInteger("code")){

            }else{
                return "error";
            }
            model.addAttribute("opt", opt);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "saleDetail::jg_refresh2";
    }

}
